package com.knshare.gen.dao;

import com.knshare.gen.config.DBConfig;
import com.knshare.gen.domain.GenTableColumn;
import com.knshare.gen.mapping.JavaTypeMapping;
import com.knshare.utils.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据层
 *
 * @author 杨静 1475654312@qq.com
 */
public class GenTableDao {

    /**
     * 查询表结构
     *
     * @param dbConfig 数据库配置
     * @param tableName 表名
     * @return 表结构
     */
    public static List<GenTableColumn> selectGenTableByName(DBConfig dbConfig, String tableName) {
        try {
            // 1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获取连接对象
            Connection conn = DriverManager.getConnection(dbConfig.getUrl(),dbConfig.getUser(),dbConfig.getPassword());
            // 3.获取SQL执行对象
            Statement st = conn.createStatement();
            // 4.执行查询语句
            ResultSet res = st.executeQuery("SELECT column_name columnName, data_type columnType, column_comment columnComment  FROM information_schema.COLUMNS WHERE table_schema = (SELECT DATABASE()) AND table_name = '"+tableName+"'");
            List<GenTableColumn> genTableColumns = new ArrayList<>();
            while(res.next()){
                GenTableColumn genTableColumn = new GenTableColumn();
                String columnName = res.getString("columnName");
                String columnComment = res.getString("columnComment");
                String columnType = res.getString("columnType");
                genTableColumn.setColumnName(StringUtils.parseSmallHump(columnName));
                genTableColumn.setColumnComment(columnComment);
                genTableColumn.setColumnType(columnType);
                genTableColumn.setJavaType(JavaTypeMapping.getJavaType(columnType));
                genTableColumns.add(genTableColumn);
            }
            res.close();
            st.close();
            conn.close();
            return genTableColumns;
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
